package com.deliveryservicesystem.presentation.desktop;

import com.deliveryservicesystem.dataaccess.DatabaseConnection;
import java.io.FileNotFoundException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;
import java.util.Formatter;
import javax.swing.table.TableModel;
import oracle.jdbc.pool.OracleDataSource;

/**
 * File Name: GenerateReport.java
 * Version:
 * Description:
 * Package: com.deliveryservicesystem.presentation.desktop
 * Author: Lance
 * Date: Jul 2, 2012
 * Editor:
 */
public class GenerateReport
{

    public void report(TableModel tableModel) throws FileNotFoundException, SQLException
    {
        int columnCount = tableModel.getColumnCount();
        int rowCount = tableModel.getRowCount();
        try (Formatter output = new Formatter("Out.txt"))
        {
            output.format("Report Printed on: %s\n", new Date().toString());
            output.format("================================================================================\n");

            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    String value = tableModel.getValueAt(i, j).toString();
                    output.format("%-20s", value);
                }
                output.format("\n", "");
            }
        }
    }

    public void report(ResultSet resultSet) throws FileNotFoundException, SQLException
    {
        DatabaseConnection instance = DatabaseConnection.getInstance();
        OracleDataSource oracleDataSource = instance.getOracleDataSource();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        try (Formatter output = new Formatter("Out.txt"))
        {
            output.format("Report of: %s\nPrinted by: %s\nPrinted on: %s\n", metaData.getTableName(1), oracleDataSource.getUser(), new Date().toString());
            output.format("================================================================================\n");

            for (int column = 0; column < columnCount; column++)
            {
                output.format("%-20s", metaData.getColumnLabel(column + 1));
            }
            output.format("\n================================================================================\n");

            while (resultSet.next())
            {
                for (int i = 1; i <= columnCount; i++)
                {
                    Object object = resultSet.getObject(i);
                    output.format("%-20s", object);
                }
                output.format("\n", "");
            }
            output.format("\nDatabase details: %s", oracleDataSource.getURL());
        }
    }
}
